//
//  WmcJoinTeamVC.swift
//  YPWatermarkCamera
//
//  Created by yupao_ios_macmini06 on 2022/9/15.
//

import SVProgressHUD
import UIKit

// MARK: - 扩展WmcJoinTeamVC + WmcNavigatorProtocol

extension WmcJoinTeamVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.joinTeamAblum]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        let vc = WmcJoinTeamVC()
        return vc
    }
}

// MARK: - 扩展WmcJoinTeamVC + WmcVMProtocol

extension WmcJoinTeamVC: WmcVMProtocol {
    typealias VMType = WmcJoinTeamVM
}

// MARK: - [WmcJoinTeamVC]

class WmcJoinTeamVC: WmcBaseVC {
    // Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    // Internal

    lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.wmc_grayH19_F5F5F5
        return view
    }()

    lazy var noteLabel: UILabel = {
        let view = UILabel()
        view.textColor = UIColor.wmc_grayH2_323233
        view.font = 18.yp.uiFont(weight: .semibold)
        view.text = "请输入团队号"
        return view
    }()

    lazy var subNoteLabel: UILabel = {
        let view = UILabel()
        view.textColor = UIColor.wmc_grayH8_8A8A99
        view.font = 14.yp.uiFont
        view.text = "请输入团队号加入"
        return view
    }()

    lazy var searchView: WmcGeneralSearchView = {
        let view = WmcGeneralSearchView()
        return view
    }()

    lazy var emptyView: WmcTeamSearchEmptyView = {
        let view = WmcTeamSearchEmptyView.emptyView(img: "team_search_empty", note: "团队不存在")
        view.isHidden = true
        return view
    }()

    override func makeUI() {
        self.title = "加入团队"

        makeNavView(style: .white, showShadow: false)
        self.addNaviLineView()

        view.addSubview(lineView)
        view.addSubview(noteLabel)
        view.addSubview(subNoteLabel)
        view.addSubview(searchView)
        view.addSubview(tableView)
        view.addSubview(emptyView)

        lineView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(1)
        }

        noteLabel.snp.makeConstraints { make in
            make.top.equalTo(lineView.snp.bottom).offset(40)
            make.left.equalTo(24)
        }

        subNoteLabel.snp.makeConstraints { make in
            make.top.equalTo(noteLabel.snp.bottom).offset(4)
            make.left.equalTo(noteLabel.snp.left)
        }

        searchView.snp.makeConstraints { make in
            make.top.equalTo(subNoteLabel.snp.bottom).offset(16)
            make.left.equalTo(24)
            make.right.equalTo(-16)
        }

        tableView.snp.makeConstraints { make in
            make.top.equalTo(searchView.snp.bottom).offset(16)
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.bottom.equalToSuperview()
        }

        emptyView.snp.makeConstraints { make in
            make.top.left.right.bottom.equalTo(tableView)
        }

        searchView.textfield.becomeFirstResponder()
    }

    override func bindViewModel() {
        self.viewModel.teams.skip(1).bind { [weak self] list in
            guard let weakSelf = self else { return }
            weakSelf.tableView.reloadData()
            weakSelf.emptyView.isHidden = list.count > 0
        }.disposed(by: rx.disposeBag)

        // tableview 是否隐藏
        self.viewModel.teams.map { $0.count < 0 }.bind(to: self.tableView.rx.isHidden).disposed(by: rx.disposeBag)
    }

    override func bindViewAction() {
        self.searchView.searchBtn.rx.controlEvent(.touchUpInside).bind { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.queryTeamInfo(teamOpenId: weakSelf.searchView.textfield.text ?? "")
            weakSelf.searchView.textfield.resignFirstResponder()
        }.disposed(by: rx.disposeBag)
    }

    // Private

    private lazy var tableView: UITableView = {
        let view = UITableView(frame: CGRect.zero, style: .plain)
        view.backgroundColor = .wmc_white_FFFFFF
        view.delegate = self
        view.dataSource = self
        view.register(WmcJoinTeamSearchCell.self, forCellReuseIdentifier: "WmcJoinTeamSearchCell")
        view.separatorStyle = .none
        view.showsVerticalScrollIndicator = false
        return view
    }()
}

// MARK: - UITableViewDelegate, UITableViewDataSource

extension WmcJoinTeamVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.viewModel.teams.value.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "WmcJoinTeamSearchCell", for: indexPath) as! WmcJoinTeamSearchCell
        let model = self.viewModel.teams.value[indexPath.section]
        cell.configure(model: model)
        cell.joinBlock = { [weak self] in
            guard let weakSelf = self else { return }
            SVProgressHUD.show()
            weakSelf.viewModel.joinTeam(teamId: model.teamId) {
                /// 加入团队跳转团队首页
                /// 获取当前加入的团队相册对象
                weakSelf.viewModel.findCurrentJoinedTeam(teamId: model.teamId ?? 0) { teamAlbum in
                    let teamAlbumModel = WmcMediaTeamAlbumModel()
                    teamAlbumModel.teamId = model.teamId ?? 0
                    teamAlbumModel.busId = "\(model.teamId ?? 0)"
                    teamAlbumModel.albumId = teamAlbum.albumId
                    teamAlbumModel.name = model.teamName ?? ""
                    teamAlbumModel.teamOpenId = teamAlbum.teamOpenId
                    /// 移除一个（以后有时间写扩展，移除任意多个到指定位置）
                    var vcs = weakSelf.navigationController?.viewControllers
                    vcs?.removeLast()
                    weakSelf.navigationController?.viewControllers = vcs ?? []
                    /// 先把我的团队相册加入导航栏栈中
                    let teamVC = WmvMyTeamVC()
                    weakSelf.navigationController?.viewControllers.append(teamVC)
                    WmcNavigatorManager.push(.teamCloudAlbum, parms: teamAlbumModel)
                    WmcHudManager.toast("已成功加入团队")
                    SVProgressHUD.dismiss()
                }
            }
        }
        return cell
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let foot = UIView(frame: CGRect(x: 0, y: 0, width: Wmc_screenWidth, height: 16))
        return foot
    }
}
